﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcContrib.UI.Grid;
using Webdiyer.WebControls.Mvc;
using hsgsSHXX.Web.Common;
namespace hsgsSHXX.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class UserController : BaseController
    {
        //
        // GET: /Admin/User/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserList(string orgNo,string FEmp_Status, int id = 1)
        {
            int pageSize = 15;
            int pageIndex = id;
            BLL.User userBLL = new BLL.User();
            List<Model.PrvUser> prvUserList = new List<Model.PrvUser>();
            int total = 0;

            prvUserList = userBLL.GetFondListByPage(pageSize, pageIndex, "", "", out total);

            foreach (Model.PrvUser prvUserModel in prvUserList)
            {
                prvUserModel.FLogID_En = GenerateUtil.Encrypt(prvUserModel.FLogID, "FLogID");
                ViewData["FProp"] = prvUserModel.FProp;
            }
            PagedList<Model.PrvUser> pagedPrvUserList = new PagedList<Model.PrvUser>(prvUserList, pageIndex, pageSize, total);
            return View(pagedPrvUserList);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        /// <summary> 
        public ActionResult EditPassword()
        {
            return EditPassword("");
        }
        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="orgNo"></param>
        /// <param name="jsAlert"></param>
        /// <param name="prvUserModel"></param>
        /// <returns></returns>
        public ActionResult AddUser(string orgNo)
        {
            return AddUser(orgNo, "", null);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="loginID"></param>
        /// <returns></returns>
        public ActionResult EditUser(string loginID)
        {
            return EditUser(loginID, "", null);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="loginID"></param>
        /// <returns></returns>
        [HttpPost]
        public string DeleteUser(string loginID_En)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string loginID = "";
            if (loginID_En != "")
            {

                BLL.User userBLL = new BLL.User();
                try
                {
                    loginID = GenerateUtil.Decrypt(loginID_En, "FLogID");
                    try
                    {
                        //这里需要判断是否有关联的记录
                        userBLL.DeleteUser(loginID);
                        jsonstr = "SUCCESS";
                    }
                    catch
                    {
                        errorMessage = "操作异常";
                    }
                }
                catch
                {
                    errorMessage = "参数错误";
                }

                if (jsonstr == "FAILED")
                {
                    jsonstr += "FAILED|" + errorMessage;
                }
            }
            return jsonstr;
        }
        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string DeleteUserList(string loginIDs)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            if (loginIDs != "")
            {
                loginIDs = loginIDs.Substring(0, loginIDs.LastIndexOf(','));
                string[] users = loginIDs.Split(new char[1] { ',' });
                List<string> userList = new List<string>();


                try
                {
                    foreach (string s in users)
                    {
                        userList.Add(GenerateUtil.Decrypt(s, "FLogID"));
                        try
                        {
                            if (userList.Contains("admin"))
                            {
                                userList.Remove("admin");
                            }
                            BLL.User userBLL = new BLL.User();
                            userBLL.DeleteUserList(userList);
                            jsonstr = "SUCCESS";
                        }
                        catch
                        {
                            errorMessage = "操作异常";
                        }
                    }
                }
                catch
                {
                    errorMessage = "参数错误";
                }


            }
            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string ResetPwd(string loginIDs)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            if (loginIDs != "")
            {
                loginIDs = loginIDs.Substring(0, loginIDs.LastIndexOf(','));
                string[] users = loginIDs.Split(new char[1] { ',' });
                List<string> userList = new List<string>();
                try
                {
                    foreach (string s in users)
                    {
                        userList.Add(GenerateUtil.Decrypt(s, "FLogID"));
                    }
                    try
                    {

                        BLL.User userBLL = new BLL.User();
                        userBLL.ResetPwdUserList(userList);
                        jsonstr = "SUCCESS";
                    }
                    catch
                    {
                        errorMessage = "操作异常";
                    }
                }
                catch
                {
                    errorMessage = "参数错误";
                }
            }
            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
        /// <summary>
        /// 保存密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SavePassword()
        {
            string loginId = OperateSession.get("LoginId");
            //string userName = OperateSession.get("UserName");
            bool isSuccess = true;
            bool isPasswordMatch = true;
            string errorMessage = "";
            string fPassword = Fetch.Post("txtFPassword").Trim();
            string passwordNew = Fetch.Post("txtPasswordNew").Trim();
            string passwordNewTwo = Fetch.Post("txtPasswordNewTwo").Trim();
            ActionResult actionResult = null;
            BLL.User userBLL = new BLL.User();
            Model.PrvUser prvUserModel = new Model.PrvUser();
            isPasswordMatch = userBLL.IsPasswordMatch(loginId, fPassword);

            //逻辑判断
            if (isSuccess)
            {
                if (passwordNew != passwordNewTwo)
                {
                    // errorMessage = "两次输入的密码不一致，请重新输入";
                    isSuccess = false;
                }
            }
            if (isSuccess)
            {
                if (isPasswordMatch == false)
                {
                    errorMessage = "原密码错误请重新输入！";
                    isSuccess = false;
                }
            }
            if (isSuccess)
            {

                try
                {
                    userBLL.UpdatePassword(loginId, passwordNew);
                    actionResult = EditPassword("SUCCESS");
                }
                catch (Exception)
                {
                    errorMessage = "操作异常:";

                }
            }
            if (actionResult == null)
            {
                actionResult = EditPassword(errorMessage);
            }
            return actionResult;

        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save()
        {
            bool isSuccess = true;
            string errorMessage = "";
            ActionResult actionResult = null;
            //model赋值
            Model.PrvUser prvUserModel = new Model.PrvUser()
            {
                FLogID =Fetch.Post("txtFLogID") != "admin"? Fetch.Post("txtFLogID").Trim():Fetch.Post("txtFLogID").Trim(),
                FName = Fetch.Post("txtFName").Trim(),
                //FProp = Fetch.Post("selFProp"),
                FProp = "U",
            };

            List<string> groupList = new List<string>();//相关用户组
            if (Fetch.Post("lstTarget") != "")
            {
                string[] grpStrings = Fetch.Post("lstTarget").Split(new char[1] { ',' });
                foreach (string s in grpStrings)
                {
                    groupList.Add(s);
                }
            }
            //数据逻辑验证
            if (prvUserModel.FLogID == "")
            {
                errorMessage = "用户ID不能为空";
                isSuccess = false;
            }
            if (isSuccess)
            {
                if (prvUserModel.FName == "")
                {
                    errorMessage = "用户姓名不能为空";
                    isSuccess = false;
                }
            }

            BLL.User userBLL = new BLL.User();
            switch (Fetch.Post("hdMethod"))
            {
                case "ADD":
                    {
                        if (isSuccess)
                        {
                            //判断是否有重复的身份证号
                            if (userBLL.ExistsLoginID(prvUserModel.FLogID))
                            {
                                errorMessage = "已存在相同的用户身份证号";
                                isSuccess = false;
                            }
                        }
                        if (isSuccess)
                        {
                            try
                            {
                                userBLL.AddUser(prvUserModel, groupList);
                                actionResult = AddUser(prvUserModel.FLogID, "SUCCESS", prvUserModel);
                            }
                            catch (Exception ee)
                            {
                                errorMessage = "操作异常" + ee.Message;
                            }
                        }
                        if (actionResult == null)
                        {
                            actionResult = AddUser(prvUserModel.FLogID, errorMessage, prvUserModel);
                        }
                        break;
                    }
                case "EDIT":
                    {
                        if (isSuccess)
                        {
                            try
                            {
                                userBLL.UpdateUser(prvUserModel, groupList);
                              
                                actionResult = EditUser(prvUserModel.FLogID, "SUCCESS", prvUserModel);
                            }
                            catch (Exception ee)
                            {
                                errorMessage = "操作异常" + ee.Message;
                            }
                        }
                        if (actionResult == null)
                        {
                            actionResult = EditUser(prvUserModel.FLogID, errorMessage, prvUserModel);
                        }
                        break;
                    }
            }

            return actionResult;
        }

        #region 私有方法
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="orgNo"></param>
        /// <param name="jsAlert"></param>
        /// <param name="prvUserModel"></param>
        /// <returns></returns>
        private ActionResult EditPassword(string jsAlert)
        {
            string fLogID = OperateSession.get("LoginId");
            string fName = OperateSession.get("UserName");
            ViewData["txtFLogID"] = fLogID;
            ViewData["txtFName"] = fName;
            if (jsAlert == "SUCCESS")
            {
                ViewData["result"] = "SUCCESS";
                jsAlert = "保存成功";
            }
            ViewData["jsAlert"] = jsAlert;
            return View("EditPassword");
        }
        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="orgNo"></param>
        /// <param name="jsAlert"></param>
        /// <param name="prvUserModel"></param>
        /// <returns></returns>
        private ActionResult AddUser(string orgNo, string jsAlert, Model.PrvUser prvUserModel)
        {
            BLL.User userBLL = new BLL.User();
            if (jsAlert == "SUCCESS")
            {
                ViewData["result"] = "SUCCESS";
                jsAlert = "保存成功";
            }
            //用户性质
            List<SelectListItem> propItems = new List<SelectListItem>();
            propItems.Add(new SelectListItem() { Text = "普通用户", Value = "U", Selected = false });
            propItems.Add(new SelectListItem() { Text = "系统管理员", Value = "S", Selected = false });


            //获取可选用户组
            List<SelectListItem> groupItems = new List<SelectListItem>();
            if (prvUserModel == null)
            {
                prvUserModel = new Model.PrvUser();
                propItems[0].Selected = true;
            }
            else
            {
                foreach (SelectListItem si in propItems)
                {
                    if (si.Value == prvUserModel.FProp)
                    {
                        si.Selected = true;
                        break;
                    }
                }
            }
            //下拉框赋值
            ViewData["propSelection"] = propItems;
            ViewData["targetUserGroup"] = new List<SelectListItem>();
            //ViewData["dutyNoSelection"] = dutyNoItems;
            //隐藏字段
            ViewData["hdMethod"] = "ADD";
            ViewData["hdOrgNo"] = orgNo;
            ViewData["jsAlert"] = jsAlert;
            return View("AddUser", prvUserModel);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="jsAlert"></param>
        /// <returns></returns>
        private ActionResult EditUser(string loginID, string jsAlert, Model.PrvUser prvUserModel)
        {
            BLL.User userBLL = new BLL.User();
            if (jsAlert == "SUCCESS")
            {
                ViewData["result"] = "SUCCESS";
                jsAlert = "保存成功";
            }
            if (prvUserModel == null)
            {
                prvUserModel = userBLL.GetUserModel(loginID);
            }
            if (prvUserModel != null)
            {
                //用户性质
                List<SelectListItem> propItems = new List<SelectListItem>();
                propItems.Add(new SelectListItem() { Text = "普通用户", Value = "U", Selected = false });
                propItems.Add(new SelectListItem() { Text = "系统管理员", Value = "S", Selected = false });

              


                //下拉框赋值
                ViewData["propSelection"] = propItems;


                //隐藏字段
                ViewData["hdMethod"] = "EDIT";
                ViewData["jsAlert"] = jsAlert;

                return View("EditUser", prvUserModel);
            }
            return null;

        }
        #endregion

    }
}
